<template>
    <div style="padding: 8px 20px">
        <el-button v-hasPerm="['sys:role:add']" :icon="CirclePlus" type="primary" @click="addNewRole">新增</el-button>
    </div>
    <el-table :data="roleList" v-loading="loading" min-width="100%">
        <el-table-column label="角色名称" prop="name" width="200"></el-table-column>
        <el-table-column label="角色编码" prop="code" width="200"></el-table-column>
        <el-table-column label="创建时间" prop="createTime" width="200"></el-table-column>
        <el-table-column label="状态" prop="name" width="200">
            <template #default="scope">
                <el-tag v-if="scope.row.status === 0" type="warning">禁用</el-tag>
                <el-tag v-else type="success">正常</el-tag>
            </template>
        </el-table-column>
        <el-table-column fixed="right" align="right" label="操作" width="160">
            <template #default="scope">
                <el-button v-hasPerm="['sys:role:edit']" type="warning" link size="small" @click="eidtDialog(scope.row)"
                    v-if="scope.row.code != 'ROOT'">编辑</el-button>
                <el-button v-hasPerm="['sys:user:delete']" type="danger" link size="small" @click="deleteRole(scope.row.id)"
                    v-if="scope.row.code != 'ROOT'">删除</el-button>
            </template>
        </el-table-column>
    </el-table>

    <el-drawer v-model="dialog" title="用户编辑" direction="rtl" :befor-close="handleClose">
        <el-form ref="roleFormRef" :model="roleForm" :rules="rules" :inline="true" label-width="auto"
            label-position="right" require-asterisk-position="right">
            <el-form-item label="角色名称">
                <el-input v-model="roleForm.name"></el-input>
            </el-form-item>
            <el-form-item label="角色编码">
                <el-input v-model="roleForm.code" placeholder="ADMIN|GUEST|VIP"></el-input>
            </el-form-item>
            <div class="row" v-for="item in allMenus">
                <el-checkbox v-model="item.checkedAll" :label="item.name"
                    @change="handleCheckAllChange(item)"></el-checkbox>
                <el-checkbox-group v-model="item.checkedIds" style="margin-left: 12px"
                    @change="handleChildChange(item)">
                    <el-checkbox v-for="child in item.children" :key="child.id" :value="child.id" :label="child.name">
                    </el-checkbox>
                </el-checkbox-group>
            </div>
            <el-button type="primary" round style="width: 100%" @click="submit">确定</el-button>
        </el-form>
    </el-drawer>
</template>

<script setup>

import MenuApi from '@/api/menu.js';
import RoleApi from '@/api/role.js';
import { ElMessage, ElMessageBox } from 'element-plus';
import { onMounted } from 'vue';

let loading = ref(true)
let roleList = ref([])
let dialog = ref(false)

let allMenus = ref([])
let rootMenus = []

const initForm = {
    id: 0,
    name: "",
    code: "",
    menuIds: []
}

let roleForm = ref(initForm)
let roleFormRef = ref()
const rules = reactive({
    name: [{ required: true, message: "请输入角色名称", trigger: "blur" }],
    code: [{ required: true, message: "请输入角色编码", trigger: "blur" }]
});

onMounted(() => {
    loadRoleList()
    loadMenuList()
})

function loadRoleList() {
    RoleApi.getRoleList().then(list => {
        roleList.value = list
        loading.value = false
    })
}

function loadMenuList() {
    MenuApi.listMenus(1, 40).then(list => {
        rootMenus = list.filter(i => i.parentId == 0)
        allMenus.value = concatChild(list)
        function concatChild(array) {
            let ls = []
            array.forEach(i => {
                if (i.children && i.children.length > 0) {
                    i.children.forEach(child => {
                        child.checkedAll = false
                        child.checkedIds = []
                        ls.push(child)
                    })
                }
            })
            return ls
        }
    })
}


async function eidtDialog(item) {
    const roleMenus = await MenuApi.getMenusByRole(item.id)
    console.log("roleMenus", roleMenus)
    item.menuIds = roleMenus
    roleForm.value = item
    dialog.value = true

    allMenus.value.forEach(a => {
        a.checkedAll = roleMenus.find(r => r == a.id) ? true : false
        a.checkedIds = roleMenus.filter(r => a.children.find(c => c.id == r))
    })
    console.log("allMenus.value", allMenus.value)
}

function deleteRole(roleId) {
    ElMessageBox.confirm(
        '是否真的删除此角色?',
        '警告',
        {
            confirmButtonText: '删除',
            cancelButtonText: '取消',
            type: 'warning',
        }
    ).then(() => {
        RoleApi.deleteRole(roleId).then(res => {
            ElMessage({
                type: 'success',
                message: '删除成功！',
            })
            loadAllMenus()
        })
    }).catch(() => {
        ElMessage({
            type: 'info',
            message: 'Delete canceled',
        })
    })
}

function handleCheckAllChange(item) {
    console.log("checkAll", item)
    if (item.checkedIds.length == 0) {
        item.checkedAll = true
        item.checkedIds = item.children.map(i => i.id)
    } else {
        item.checkedAll = false
        item.checkedIds = []
    }
}
function handleChildChange(item) {
    item.checkedAll = item.checkedIds.length > 0
}

function submit() {
    let allMenuIds = rootMenus.map(r => r.id)
    allMenus.value.forEach(a => {
        if (a.checkedAll) {
            allMenuIds.push(a.id)
            allMenuIds = allMenuIds.concat(a.checkedIds)
        }
    })
    roleForm.value.menuIds = allMenuIds
    roleFormRef.value.validate((isValid) => {
        if (isValid) {
            RoleApi.addOrUpdateRole(roleForm.value).then(res => {
                if (res) {
                    dialog.value = false
                    ElMessage({
                        message: '添加或更新角色成功',
                        type: 'success',
                    })
                    loadRoleList()
                }

            })
        }
    })
}

function addNewRole() {
    dialog.value = true
}

function handleClose() {
    dialog.value = false
    roleForm.value = initForm
}
</script>

<style lang="scss">
.row {
    display: flex;
    flex-direction: row;
    flex-wrap: wrap;
}
</style>